package com.wang.API;

import com.wang.bean.Lesson;
import com.wang.bean.Result;
import com.wang.bean.SysUserEntity;
import com.wang.config.ShiroUtils;
import com.wang.service.UserService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("api")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    public HttpServletRequest request;

    @RequestMapping(value = "/finduserbyid")
    @RequiresPermissions("sys:user:finduserbyid")
    public Result finduserbyid(@RequestBody Long user_id){
        Result result = new Result();
        if (user_id == 0){
            result.setCode("111");
            return result;
        }
        SysUserEntity sysUserEntity = userService.selectOneById(user_id);
        if (sysUserEntity != null){
            result.setCode("105");
            result.setData(sysUserEntity);
            return result;
        } else {
            result.setCode("110");
            return result;
        }
    }

    @RequestMapping(value = "/getthisuser")
    @RequiresPermissions("sys:user:getthisuser")
    public Result getthisuser(){
        Result result = new Result();
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        if (userEntity == null){
            result.setCode("108");
            return result;
        } else {
            SysUserEntity sysUserEntity = userService.selectOneById(userEntity.getUser_id());
            result.setCode("105");
            result.setData(sysUserEntity);
            return result;
        }
    }

    @RequestMapping(value = "/updatethisuser")
    @RequiresPermissions("sys:user:updatethisuser")
    public Result updatethisuser(@RequestBody SysUserEntity sysUserEntity){
        Result result = new Result();
        if (sysUserEntity == null){
            result.setCode("116");
            return result;
        }
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        if (userEntity == null){
            result.setCode("108");
            return result;
        }
        sysUserEntity.setUser_id(userEntity.getUser_id());
        userService.updatethisuser(sysUserEntity);
        result.setCode("104");
        result.setData(userService.selectOneById(userEntity.getUser_id()));
        return result;
    }

    @RequestMapping(value = "/finduserlot")
    @RequiresPermissions("sys:user:finduserlot")
    public Result finduserlot(String username){
        Result result = new Result();
        List<SysUserEntity> sysUserEntities = userService.selectLot(username);
        result.setCode("112");
        result.setData(sysUserEntities);
        return result;
    }

    @RequestMapping(value = "/finduserlot1")
    @RequiresPermissions("sys:user:finduserlot1")
    public Result finduserlot1(@RequestBody SysUserEntity sysUserEntity){
        Result result = new Result();
        if (sysUserEntity == null){
            result.setCode("116");
            return result;
        }
        List<SysUserEntity> sysUserEntities = userService.selectLot1(sysUserEntity);
        result.setCode("112");
        result.setData(sysUserEntities);
        return result;
    }

    @RequestMapping(value = "/createuser")
    @RequiresPermissions("sys:user:createuser")
    public Result createuser(@RequestBody SysUserEntity sysUserEntity){
        Result result = new Result();
        if (sysUserEntity == null){
            result.setCode("116");
            return result;
        }
        if (sysUserEntity.getUsername() == null || "".equals(sysUserEntity.getUsername())){
            result.setCode("113");
            return result;
        }
        if (sysUserEntity.getPassword() == null || "".equals(sysUserEntity.getPassword())){
            result.setCode("114");
            return result;
        }
        if (userService.selectOne(sysUserEntity.getUsername()) != null){
            result.setCode("107");
            return result;
        }
        String salt = "123";
        sysUserEntity.setPassword(ShiroUtils.sha256(sysUserEntity.getPassword(),salt));
        sysUserEntity.setSalt(salt);
        if (sysUserEntity.getStatus() == null){
            sysUserEntity.setStatus(1);
        } else {
            if (sysUserEntity.getStatus() > 0){
                sysUserEntity.setStatus(1);
            } else {
                sysUserEntity.setStatus(0);
            }
        }
        sysUserEntity.setCreateTime(new Date());
        userService.insertuser(sysUserEntity);
        result.setCode("106");
        result.setData(userService.selectOne(sysUserEntity.getUsername()));
        return result;
    }

    @RequestMapping(value = "/deleteuserbyid")
    @RequiresPermissions("sys:user:deleteuserbyid")
    public Result deleteuserbyid(@RequestBody Long user_id){
        Result result = new Result();
        if (userService.selectOneById(user_id) == null){
            result.setCode("110");
            return result;
        }
        userService.deleteuserbyid(user_id);
        result.setCode("115");
        return result;
    }

    @RequestMapping(value = "/updatethispassword")
    @RequiresPermissions("sys:user:updatethispassword")
    public Result updatethispassword(@RequestBody String password){
        Result result = new Result();
        if (password == null || "".equals(password)){
            result.setCode("114");
            return result;
        }
        if (ShiroUtils.getUserEntity() == null){
            result.setCode("108");
            return result;
        }
        if (userService.selectOneById(ShiroUtils.getUserId()) == null){
            result.setCode("110");
            return result;
        }
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setUser_id(ShiroUtils.getUserId());
        String salt = "123";
        sysUserEntity.setPassword(ShiroUtils.sha256(password,salt));
        userService.updatepassword(sysUserEntity);
        result.setCode("103");
        return result;
    }

    @RequestMapping(value = "/updateotherpassword")
    @RequiresPermissions("sys:user:updateotherpassword")
    public Result updateotherpassword(@RequestBody SysUserEntity sysUserEntity){
        Result result = new Result();
        if (sysUserEntity == null){
            result.setCode("116");
            return result;
        }
        if (sysUserEntity.getUser_id() == null){
            result.setCode("111");
            return result;
        }
        if (sysUserEntity.getPassword() == null || "".equals(sysUserEntity.getPassword())){
            result.setCode("114");
            return result;
        }
        if (userService.selectOneById(sysUserEntity.getUser_id()) == null){
            result.setCode("110");
            return result;
        }
        String salt = "123";
        sysUserEntity.setPassword(ShiroUtils.sha256(sysUserEntity.getPassword(),salt));
        userService.updatepassword(sysUserEntity);
        result.setCode("103");
        return result;
    }

    @RequestMapping(value = "/importuser")
    @RequiresPermissions("sys:user:importuser")
    public Result importUser(MultipartFile file){
        Result result = new Result();

        String message = "未知错误！";
        String fileName = file.getOriginalFilename();

        try {
            message = userService.importUser(fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(message);
        result.setCode("117");
        result.setMessage(message);
        return result;
    }

    @RequestMapping(value = "/getuserexcel")
    @RequiresPermissions("sys:user:getuserexcel")
    public Result getUserExcel(HttpServletResponse response) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("The World's 500 Enterprises");
        HSSFCell cell1 = demoSheet.createRow(0).createCell(0);

        String fileName = "user"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = { "用户ID", "用户名", "密码","盐", "邮箱","电话","状态"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        String[] template = { "1(Long，非必填)", "admin(String，必填)", "123456(String，必填)","123(String，非必填)", "123456789@qq.com(String，非必填)","13211111111(String，非必填)","1(1或0，非必填)"};
        HSSFRow row1 = sheet.createRow(1);
        for(int i=0;i<template.length;i++){
            HSSFCell cell = row1.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(template[i]);
            cell.setCellValue(text);
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
        Result result = new Result();
        result.setMessage("成功！");
        return result;
    }

}
